<template>
<div>
  <div :id="id" :class="className" :style="{ height: height, width: width }" />
</div>
</template>

<script>
  import * as echarts from 'echarts';
  import resize from "./mixins/resize.js";
  export default {
    mixins: [resize],
    watch: {
      options: {
        handler (options) {
          this.chart.setOption(options);
        },
        deep: true,
      },
    },
    props: {
      className: {
        type: String,
        default: "chart",
      },
      width: {
        type: String,
        default: "100%",
      },
      height: {
        type: String,
        default: "300px",
      },
      options: {
        type: Object,
      },
    },
    data () {
      return {
        id: "",
        chart: null,
      };
    },
    beforeMount () {
      this.id = this.random()
    },
    mounted () {
      setTimeout(() => {
        this.initChart(this.options);
      }, 10)

    },
    beforeDestroy () {
      if (!this.chart) {
        return;
      }
      this.chart.dispose();
      this.chart = null;
    },
    methods: {
      random () {
        let len = 8;
        let $chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz";
        let maxPos = $chars.length;
        let id = "";
        for (let i = 0; i < len; i++) {
          id += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return id;
      },
      initChart (options) {
        this.chart = echarts.init(document.getElementById(this.id), "macarons");
        this.chart.setOption(options);
      },
    },
  };
</script>
